<template>
  <div class="merchant-profile">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>个人信息</h2>
    </div>

    <a-row :gutter="16">
      <a-col :span="16">
        <!-- 基本信息卡片 -->
        <a-card class="profile-card">
          <template #title>基本信息</template>
          <a-form :model="profileForm" layout="vertical">
            <a-row :gutter="16">
              <a-col :span="8">
                <div class="avatar-wrapper">
                  <a-upload
                    action="/api/upload"
                    :show-file-list="false"
                    :before-upload="beforeAvatarUpload"
                    @change="handleAvatarChange"
                  >
                    <div class="avatar-container">
                      <img
                        v-if="profileForm.avatar"
                        :src="profileForm.avatar"
                        class="avatar-image"
                      />
                      <div v-else class="avatar-placeholder">
                        <icon-camera />
                      </div>
                      <div class="avatar-mask">
                        <icon-edit />
                        <span>更换头像</span>
                      </div>
                    </div>
                  </a-upload>
                </div>
              </a-col>
              <a-col :span="16">
                <a-form-item field="merchantName" label="商家名称">
                  <a-input
                    v-model="profileForm.merchantName"
                    placeholder="请输入商家名称"
                  />
                </a-form-item>
                <a-form-item field="realName" label="真实姓名">
                  <a-input
                    v-model="profileForm.realName"
                    placeholder="请输入真实姓名"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-form-item field="phone" label="联系电话">
              <a-input-group>
                <a-input
                  v-model="profileForm.phone"
                  placeholder="请输入联系电话"
                  :style="{ width: '320px' }"
                />
                <a-button type="outline" @click="handleChangePhone">
                  更换手机号
                </a-button>
              </a-input-group>
            </a-form-item>

            <a-form-item field="email" label="电子邮箱">
              <a-input-group>
                <a-input
                  v-model="profileForm.email"
                  placeholder="请输入电子邮箱"
                  :style="{ width: '320px' }"
                />
                <a-button type="outline" @click="handleChangeEmail">
                  更换邮箱
                </a-button>
              </a-input-group>
            </a-form-item>

            <a-form-item field="introduction" label="商家简介">
              <a-textarea
                v-model="profileForm.introduction"
                placeholder="请输入商家简介"
                :max-length="200"
                show-word-limit
              />
            </a-form-item>

            <a-form-item>
              <a-button type="primary" @click="handleSaveProfile">
                保存修改
              </a-button>
            </a-form-item>
          </a-form>
        </a-card>

        <!-- 认证信息卡片 -->
        <a-card class="profile-card">
          <template #title>认证信息</template>
          <a-descriptions :data="certificationInfo" layout="inline-vertical">
            <template #label="{ label }">
              {{ label }}
            </template>
            <template #value="{ value }">
              <template v-if="typeof value === 'object'">
                <a-tag :color="value.color">{{ value.text }}</a-tag>
              </template>
              <template v-else>
                {{ value }}
              </template>
            </template>
          </a-descriptions>
        </a-card>

        <!-- 账号安全卡片 -->
        <a-card class="profile-card">
          <template #title>账号安全</template>
          <a-list>
            <a-list-item>
              <div class="security-item">
                <div class="security-info">
                  <div class="security-title"><icon-lock /> 登录密码</div>
                  <div class="security-desc">定期更换密码可以保护账号安全</div>
                </div>
                <div class="security-action">
                  <a-button type="text" @click="handleChangePassword">
                    修改密码
                  </a-button>
                </div>
              </div>
            </a-list-item>
            <a-list-item>
              <div class="security-item">
                <div class="security-info">
                  <div class="security-title"><icon-mobile /> 手机绑定</div>
                  <div class="security-desc">
                    已绑定：{{ maskPhone(profileForm.phone) }}
                  </div>
                </div>
                <div class="security-action">
                  <a-button type="text" @click="handleChangePhone">
                    更换手机号
                  </a-button>
                </div>
              </div>
            </a-list-item>
            <a-list-item>
              <div class="security-item">
                <div class="security-info">
                  <div class="security-title"><icon-email /> 邮箱绑定</div>
                  <div class="security-desc">
                    已绑定：{{ maskEmail(profileForm.email) }}
                  </div>
                </div>
                <div class="security-action">
                  <a-button type="text" @click="handleChangeEmail">
                    更换邮箱
                  </a-button>
                </div>
              </div>
            </a-list-item>
          </a-list>
        </a-card>
      </a-col>

      <a-col :span="8">
        <!-- 店铺等级卡片 -->
        <a-card class="profile-card">
          <template #title>店铺等级</template>
          <div class="level-info">
            <div class="current-level">
              <icon-shop />
              <span class="level-text">{{ shopLevel.currentLevel }}</span>
            </div>
            <a-progress
              :percent="shopLevel.progress"
              :show-text="false"
              :stroke-width="8"
              :track-color="'var(--color-fill-3)'"
            />
            <div class="level-progress">
              <span>当前成长值：{{ shopLevel.currentPoints }}</span>
              <span>下一级：{{ shopLevel.nextLevelPoints }}</span>
            </div>
            <div class="level-benefits">
              <h4>当前等级权益：</h4>
              <ul>
                <li v-for="(benefit, index) in shopLevel.benefits" :key="index">
                  {{ benefit }}
                </li>
              </ul>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 修改密码弹窗 -->
    <a-modal
      v-model:visible="showPasswordModal"
      title="修改密码"
      @ok="handlePasswordConfirm"
      @cancel="closePasswordModal"
    >
      <a-form :model="passwordForm" layout="vertical">
        <a-form-item
          field="oldPassword"
          label="当前密码"
          :rules="[{ required: true, message: '请输入当前密码' }]"
        >
          <a-input-password
            v-model="passwordForm.oldPassword"
            placeholder="请输入当前密码"
          />
        </a-form-item>
        <a-form-item
          field="newPassword"
          label="新密码"
          :rules="[
            { required: true, message: '请输入新密码' },
            { minLength: 8, message: '密码长度不能小于8位' },
          ]"
        >
          <a-input-password
            v-model="passwordForm.newPassword"
            placeholder="请输入新密码"
          />
        </a-form-item>
        <a-form-item
          field="confirmPassword"
          label="确认新密码"
          :rules="[
            { required: true, message: '请确认新密码' },
            {
              validator: (value) =>
                value === passwordForm.newPassword || '两次输入的密码不一致',
            },
          ]"
        >
          <a-input-password
            v-model="passwordForm.confirmPassword"
            placeholder="请再次输入新密码"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 更换手机号弹窗 -->
    <a-modal
      v-model:visible="showPhoneModal"
      title="更换手机号"
      @ok="handlePhoneConfirm"
      @cancel="closePhoneModal"
    >
      <a-form :model="phoneForm" layout="vertical">
        <a-form-item
          field="newPhone"
          label="新手机号"
          :rules="[{ required: true, message: '请输入新手机号' }]"
        >
          <a-input v-model="phoneForm.newPhone" placeholder="请输入新手机号" />
        </a-form-item>
        <a-form-item
          field="verifyCode"
          label="验证码"
          :rules="[{ required: true, message: '请输入验证码' }]"
        >
          <a-input-group>
            <a-input
              v-model="phoneForm.verifyCode"
              placeholder="请输入验证码"
              :style="{ width: '320px' }"
            />
            <a-button @click="handleSendCode">
              {{ countdown > 0 ? `${countdown}s后重新获取` : "获取验证码" }}
            </a-button>
          </a-input-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 更换邮箱弹窗 -->
    <a-modal
      v-model:visible="showEmailModal"
      title="更换邮箱"
      @ok="handleEmailConfirm"
      @cancel="closeEmailModal"
    >
      <a-form :model="emailForm" layout="vertical">
        <a-form-item
          field="newEmail"
          label="新邮箱"
          :rules="[
            { required: true, message: '请输入新邮箱' },
            { type: 'email', message: '请输入正确的邮箱格式' },
          ]"
        >
          <a-input v-model="emailForm.newEmail" placeholder="请输入新邮箱" />
        </a-form-item>
        <a-form-item
          field="verifyCode"
          label="验证码"
          :rules="[{ required: true, message: '请输入验证码' }]"
        >
          <a-input-group>
            <a-input
              v-model="emailForm.verifyCode"
              placeholder="请输入验证码"
              :style="{ width: '320px' }"
            />
            <a-button @click="handleSendEmailCode">
              {{
                emailCountdown > 0
                  ? `${emailCountdown}s后重新获取`
                  : "获取验证码"
              }}
            </a-button>
          </a-input-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { Message } from "@arco-design/web-vue";
import {
  IconCamera,
  IconEdit,
  IconLock,
  IconMobile,
  IconEmail,
  IconShop,
  IconCheckCircleFill,
} from "@arco-design/web-vue/es/icon";

// 个人信息表单
const profileForm = reactive({
  avatar: "",
  merchantName: "贵港文创商城",
  realName: "张三",
  phone: "13800138000",
  email: "example@example.com",
  introduction: "专注文创产品销售，提供优质的文化创意商品。",
});

// 认证信息
const certificationInfo = [
  {
    label: "实名认证",
    value: { text: "已认证", color: "green" },
  },
  {
    label: "身份证号",
    value: "450800********1234",
  },
  {
    label: "营业执照",
    value: { text: "已认证", color: "green" },
  },
  {
    label: "统一社会信用代码",
    value: "91450800********1234",
  },
  {
    label: "经营类目",
    value: "文化用品 / 创意商品",
  },
  {
    label: "认证时间",
    value: "2024-01-01",
  },
];

// 店铺等级信息
const shopLevel = reactive({
  currentLevel: "黄金店铺",
  progress: 75,
  currentPoints: 7500,
  nextLevelPoints: 10000,
  benefits: [
    "商品数量上限：1000个",
    "享受平台流量扶持",
    "专属客服通道",
    "优先活动报名资格",
  ],
});

// 修改密码相关
const showPasswordModal = ref(false);
const passwordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 更换手机号相关
const showPhoneModal = ref(false);
const phoneForm = reactive({
  newPhone: "",
  verifyCode: "",
});
const countdown = ref(0);

// 更换邮箱相关
const showEmailModal = ref(false);
const emailForm = reactive({
  newEmail: "",
  verifyCode: "",
});
const emailCountdown = ref(0);

// 头像上传
const beforeAvatarUpload = (file) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJpgOrPng) {
    Message.error("只能上传 JPG 或 PNG 格式的图片！");
    return false;
  }
  if (!isLt2M) {
    Message.error("图片大小不能超过 2MB！");
    return false;
  }
  return true;
};

const handleAvatarChange = (info) => {
  if (info.file.status === "done") {
    profileForm.avatar = info.file.response.url;
    Message.success("头像上传成功");
  }
};

// 保存个人信息
const handleSaveProfile = () => {
  Message.success("个人信息保存成功");
};

// 修改密码
const handleChangePassword = () => {
  showPasswordModal.value = true;
};

const handlePasswordConfirm = () => {
  Message.success("密码修改成功");
  closePasswordModal();
};

const closePasswordModal = () => {
  showPasswordModal.value = false;
  Object.assign(passwordForm, {
    oldPassword: "",
    newPassword: "",
    confirmPassword: "",
  });
};

// 更换手机号
const handleChangePhone = () => {
  showPhoneModal.value = true;
};

const handleSendCode = () => {
  if (countdown.value > 0) return;
  countdown.value = 60;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value === 0) {
      clearInterval(timer);
    }
  }, 1000);
  Message.success("验证码已发送");
};

const handlePhoneConfirm = () => {
  Message.success("手机号更换成功");
  closePhoneModal();
};

const closePhoneModal = () => {
  showPhoneModal.value = false;
  Object.assign(phoneForm, {
    newPhone: "",
    verifyCode: "",
  });
};

// 更换邮箱
const handleChangeEmail = () => {
  showEmailModal.value = true;
};

const handleSendEmailCode = () => {
  if (emailCountdown.value > 0) return;
  emailCountdown.value = 60;
  const timer = setInterval(() => {
    emailCountdown.value--;
    if (emailCountdown.value === 0) {
      clearInterval(timer);
    }
  }, 1000);
  Message.success("验证码已发送");
};

const handleEmailConfirm = () => {
  Message.success("邮箱更换成功");
  closeEmailModal();
};

const closeEmailModal = () => {
  showEmailModal.value = false;
  Object.assign(emailForm, {
    newEmail: "",
    verifyCode: "",
  });
};

// 工具函数
const maskPhone = (phone) => {
  return phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
};

const maskEmail = (email) => {
  const [username, domain] = email.split("@");
  const maskedUsername = username.charAt(0) + "*".repeat(username.length - 1);
  return `${maskedUsername}@${domain}`;
};
</script>

<style lang="scss" scoped>
.merchant-profile {
  padding: 24px;

  .page-header {
    @apply mb-6;

    h2 {
      @apply text-xl font-medium m-0;
    }
  }

  .profile-card {
    @apply mb-6;
  }

  .avatar-wrapper {
    @apply flex justify-center items-center;

    .avatar-container {
      @apply relative w-32 h-32 rounded-full overflow-hidden cursor-pointer;

      .avatar-image {
        @apply w-full h-full object-cover;
      }

      .avatar-placeholder {
        @apply w-full h-full bg-gray-200 flex items-center justify-center text-gray-400;
      }

      .avatar-mask {
        @apply absolute inset-0 bg-black bg-opacity-50 flex flex-col items-center justify-center text-white opacity-0 transition-opacity duration-300;

        &:hover {
          @apply opacity-100;
        }
      }
    }
  }

  .level-info {
    .current-level {
      @apply flex items-center gap-2 text-lg font-medium mb-4;

      .icon {
        @apply text-primary-500;
      }
    }

    .level-progress {
      @apply flex justify-between text-sm text-gray-500 mt-2 mb-4;
    }

    .level-benefits {
      h4 {
        @apply text-base font-medium mb-2;
      }

      ul {
        @apply list-disc list-inside text-sm text-gray-600 space-y-1;
      }
    }
  }
}
</style>
